package org.lex.checksum.core;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.lex.checksum.utils.HexEncoder;

public class MessageDigestAlgorithm implements Algorithm {
	private final String algorithm;
	private MessageDigest md = null;

	public MessageDigestAlgorithm(String algorithm) {
		this.algorithm = algorithm;
		try {
			this.md = MessageDigest.getInstance(algorithm);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
	}

	public void reset() {
		md.reset();
	}

	public void update(byte[] b, int offset, int len) {
		md.update(b, offset, len);
	}

	public String finish() {
		byte[] result = md.digest();
		return HexEncoder.toHex(result);
	}

	@Override
	public MessageDigestAlgorithm clone() {
		return new MessageDigestAlgorithm(this.algorithm);
	}

}
